package com.belief.aidaroe.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.belief.aidaroe.licenseUtils.CommonUtil;
import com.belief.aidaroe.licenseUtils.LicenseAuth;
import com.belief.aidaroe.models.LicenseInfo;
import com.belief.aidaroe.service.LicenseService;
import com.belief.aidaroe.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 版权：(C) 版权所有 苏州彼立孚数据科技有限公司
 * <简述>
 * <详细描述>
 *
 * @author Lynkin
 * @create: 2021-07-14 10:16
 */
@Controller
//@RequestMapping("/license")
public class LicenseController {

    //行政区划，替代物理地址，加密只用了硬盘序号
    public String xzqh = "0512";

    //系统名称
    public String xm_name = "AIDAROE";

    @Autowired
    private LicenseService licenseService;

    /**
     * 单独的验证授权的方法，该方法中拿授权文件中的授权码，解密成一个
     * 系统名称+行政区划+硬盘序号+授权时间+授权截止时间串，
     * 然后获取本机的系统名称+行政区划+硬盘序号串，两者进行比较，如果验证通过，再判断时间是否
     * 到期，如果都通过，则返回验证通过。
     * 否则，使用本机的系统名称+行政区划+硬盘序号串，加密成一个申请码返回给前台
     *
     * @return
     */
    @CrossOrigin
    @RequestMapping( "/checkLicense")
    public String checkLicense(String authorizeCode, Model model) {
        Map resultMap = new HashMap();
        try {
            if (StrUtil.isNotBlank(authorizeCode)) {
                if (CheckAuthorizeCode.checkAuthorizeCode(authorizeCode, xm_name, xzqh)) {
                    resultMap.put("success", true);
                    resultMap.put("msg", "授权成功");
                    //写进注册表
//                    System.loadLibrary("regedit1");
//                    RegeditAdd regeditAdd = new RegeditAdd();
//                    String s = regeditAdd.regeditAdd(authorizeCode);
//                    System.out.println(s);
                    RegeditUtils.writeValue("aidaroe", authorizeCode);
                    String content = DESUtils.decrypt(authorizeCode);
                    model.addAttribute("time", content.split(",")[3]);
                    return "success";
                } else {
                    model.addAttribute("msg", "授权码错误");
                    return "license";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultMap.put("success", false);
        resultMap.put("msg", "系统未授权，请授权后登录");

//        resultMap.put("license", LicenseCode.getApplyCode(xm_name, xzqh));
        return "license";
    }

    /**
     * <简介> 获取申请码
     * <详细描述>
     * @author Lynkin
     * @param
     * @return
     */
    @CrossOrigin
    @GetMapping ("/getApplyCode")
    @ResponseBody
    public Object getApplyCode() {
        Map resultMap = new HashMap();
        resultMap.put("license", LicenseCode.getApplyCode(xm_name, xzqh));
        return resultMap;
    }


    /**
     * <简介> 跳转到登录页面
     * <详细描述>
     * @author Lynkin
     * @param
     * @return
     */
    @RequestMapping("/aidaroe")
    public String aidaroe(Model model) {
        Map resultMap = new HashMap();
        //去注册表获取信息
        String aidaroe = RegeditUtils.getValue("aidaroe");
        if (StrUtil.isNotBlank(aidaroe)) {
            try {
                if (CheckAuthorizeCode.checkAuthorizeCode(aidaroe, xm_name, xzqh)) {
                    resultMap.put("success", true);
                    resultMap.put("msg", "授权成功");
                    String content = DESUtils.decrypt(aidaroe);
                    model.addAttribute("time", content.split(",")[3]);
                    return "success";
                } else {
//                    model.addAttribute("msg", "授权码错误");
                    return "authLogin";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "authLogin";
    }

    /**
     * <简介> 跳转到登录页面
     * <详细描述>
     * @author Lynkin
     * @param
     * @return
     */
    @RequestMapping("/authLogin")
    public String authLogin(Model model) {
        Map resultMap = new HashMap();
        //去注册表获取信息
        String aidaroe = RegeditUtils.getValue("aidaroe");
        if (StrUtil.isNotBlank(aidaroe)) {
            try {
                if (CheckAuthorizeCode.checkAuthorizeCode(aidaroe, xm_name, xzqh)) {
                    resultMap.put("success", true);
                    resultMap.put("msg", "授权成功");
                    String content = DESUtils.decrypt(aidaroe);
                    model.addAttribute("time", content.split(",")[3]);
                    return "success";
                } else {
//                    model.addAttribute("msg", "授权码错误");
                    return "authLogin";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "authLogin";
    }

    /**
     * <简介> 跳转到生成授权码页面
     * <详细描述>
     * @author Lynkin
     * @param
     * @return
     */
    @RequestMapping("/toGetAuthorizeCode")
    public String toGetAuthorizeCode() {
        return "getAuthorizeCode";
    }


    /**
     * <简介> 获取授权码
     * <详细描述>
     * @author Lynkin
     * @param
     * @return
     */
    @CrossOrigin
    @PostMapping("/getAuthorizeCode")
    @ResponseBody
    public Object getAuthorizeCode(String applyCode, Integer monthNum) {
        Map resultMap = new HashMap();
        String code =  null;
        try {
            code = DESUtils.decrypt(applyCode);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("success", false);
            resultMap.put("msg", "申请码错误");
            return resultMap;
        }
        String[] codeContent = code.split(",");
        if (codeContent.length != 4) {
            resultMap.put("success", false);
            resultMap.put("msg", "申请码错误");
            return resultMap;
        }


        //过期时间 增加月
        DateTime endDate = DateUtil.offsetMonth(new Date(), monthNum);
        String endDateString = DateUtil.format(endDate, "yyyy-MM-dd");
        //拼接
        String authorizeCode = codeContent[0] + "," + codeContent[1] + "," + codeContent[2] + "," + endDateString;

        try {
            //加密
            authorizeCode = DESUtils.encrypt(authorizeCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        LicenseInfo licenseInfo = new LicenseInfo();
        licenseInfo.setAuthorizeTime(new Date());
        licenseInfo.setProjectName(codeContent[0]);
        licenseInfo.setAddressNo(codeContent[1]);
        licenseInfo.setMachineNo(codeContent[2]);
        licenseInfo.setAuthorizeEndTime(endDate);
        licenseInfo.setAuthorizeCode(authorizeCode);
        licenseInfo.setApplyCode(applyCode);
        licenseService.saveLicense(licenseInfo);



        resultMap.put("success", true);
        resultMap.put("authorizeCode", authorizeCode);
        resultMap.put("msg", "获取授权码成功");
        return resultMap;
    }

    @RequestMapping(value="/licenseauth",method= RequestMethod.POST)
    @ResponseBody
    public Map<Object,Object> licenseauth(MultipartHttpServletRequest multiReq){
        Map<Object,Object>  map = new HashMap<Object,Object>();
        try {
            String savePath = ResourceUtils.getURL("src/main/resources/static/lic").getPath();
            MultipartFile file = multiReq.getFile("file");
            String filename = file.getOriginalFilename();
            File uploadfile = new File(savePath + "\\" + filename);
            if (!uploadfile.exists()){
                //获取item中的上传文件的输入流
                InputStream in = file.getInputStream();
                //创建一个文件输出流
                FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);
                //创建一个缓冲区
                byte buffer[] = new byte[1024];
                //判断输入流中的数据是否已经读完的标识
                int len = 0;
                //循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据
                while((len=in.read(buffer))>0){
                    //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
                    out.write(buffer, 0, len);
                }
                //关闭输入流
                in.close();
                //关闭输出流
                out.close();
            }
            map.put("executestatus","1");

        }catch (Exception e){
            e.printStackTrace();
            map.put("executestatus","0");
        }

        return map;
    }


    @RequestMapping(value="/login/getmachinecode",method= RequestMethod.POST)
    @ResponseBody
    public Map<Object,Object> getmachinecode(@RequestBody Map<String,Object> reqMap){
        Map<Object,Object>  map = new HashMap<Object,Object>();
        try {
            String machineCode = LicenseAuth.getMachineCode();
            map.put("machinecode", machineCode);
            map.put("executestatus","1");
        }catch (Exception e){
            map.put("executestatus","0");
        }
        return map;
    }

    @RequestMapping(value="createLicense",method= RequestMethod.POST)
    @ResponseBody
    public Map<Object,Object> createLicense(@RequestBody Map<String,Object> reqMap,HttpServletRequest request){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Map<Object,Object>  map = new HashMap<Object,Object>();
        try {
            String LicensePath= MessageFormat.format("D:/{0}.lic",sdf.format(new Date())+ UUID.randomUUID().toString().replace("-","").substring(0,8));
            String prikeypath = "d:/license/yblog.keystore";
            String machinecode =reqMap.get("machinecode").toString();
            String islimit =reqMap.get("islimit").toString();
            String liclimit =reqMap.get("liclimit").toString();
            LicenseAuth.getLicense(islimit,liclimit,machinecode,LicensePath,prikeypath);
            String downloadurl = CommonUtil.GetProjectUrl(request)+"attach/tempfiledownload?filepath="+ URLEncoder.encode(LicensePath);
            map.put("downloadurl",downloadurl);
            map.put("executestatus","1");
        }catch (Exception e){
            e.printStackTrace();
            map.put("executestatus","0");
        }
        return map;
    }

    @RequestMapping("/getLicense")
    public String getLicense() {
        return "getLicense";
    }

}
